package com.gaomall.seckill.controller;

import com.gaomall.seckill.enums.ResponseStatusCode;
import com.gaomall.seckill.exception.GoodsException;
import com.gaomall.seckill.utils.ResultVOUtil;
import com.gaomall.seckill.validator.UserForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Locale;

@RestController
// lombok + @Slf4j 日志使用 log.error();
@Slf4j
public class UserControllor {

    /**
     * 方式一：@Valid UserForm userForm
     *
     * 方式二：@Valid User user 实体类
     *
     *
     * @param userForm
     * @param bindingResult
     * @return
     */
    @PostMapping("/testFrom")
    public ResultVOUtil addUser(@Valid UserForm userForm , BindingResult bindingResult ){
        //判断表单校验后有没有错误
        if(bindingResult.hasErrors()){
            log.error( "【用户注册】参数不正确，userForm={}" , userForm);

            throw new GoodsException(ResponseStatusCode.ERROR.getReturn_code(), bindingResult.getFieldError().getDefaultMessage());

//            StringBuffer msg=new StringBuffer();
//            //如果有校验不通过的
//            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            Locale locale = LocaleContextHolder.getLocale();//得到本地化对象
//            for (FieldError fieldError : fieldErrors) {
//                String errorMsg=messageSource.getMessage(fieldError,locale);
//                msg.append(fieldError.getField()+":"+errorMsg+" ;");
//            }
//            msg.toString();


        }

        ResultVOUtil.error(ResponseStatusCode.ERROR.getReturn_code(),bindingResult.getFieldError().getDefaultMessage());
//       ???
        return null;
        }



}
